package com.ydl.iec.demo;

import com.ydl.iec.iec104.enums.QualifiersEnum;
import com.ydl.iec.iec104.enums.TypeIdentifierEnum;
import com.ydl.iec.iec104.message.MessageDetail;
import com.ydl.iec.iec104.message.MessageInfo;
import com.ydl.iec.iec104.server.handler.ChannelHandler;
import com.ydl.iec.util.ByteUtil;

import java.util.*;

public class GeneralCallString {

    public static void setTotalCall(ChannelHandler ctx){

        sendData(ctx,TypeIdentifierEnum.onePointTeleindication,1);
        sendData(ctx,TypeIdentifierEnum.shortFloatingPointTelemetry,2);
        sendData(ctx,TypeIdentifierEnum.onePointTelecontrol,3);
    }

    private static void sendData(ChannelHandler ctx,TypeIdentifierEnum typeIdentifierEnum,int pointType) {
        byte[] control = new byte[4];

        //SQ=0 length =1
        boolean isContinuous = false;
        // 传输原因
        short transferReason = 0x14;
        // true：1 ; false ： 0
        boolean isTest = false;
        // true:0 false;1
        boolean isPN = true;
        short terminalAddress = 1;
        //连续地址时设置messageAddress
        int messageAddress = 99;
        // 老板限定词
        QualifiersEnum qualifiers = QualifiersEnum.qualityQualifiers;
        switch(pointType) {
            case 1:qualifiers = QualifiersEnum.onePointTime;break;
            case 2:qualifiers = QualifiersEnum.qualityQualifiers;break;
            case 3:qualifiers = QualifiersEnum.onePointTeleControl;break;
        }

        List<MessageInfo> messages = new ArrayList<>();
        QualifiersEnum finalQualifiers = qualifiers;
        Test.resourceManage.getResources().forEach((resourceId,resource)->{
            if(resource.getControlSwitch()==0)return;
            resource.getPoints().forEach((pointId,point)->{
                if(point.getPointType()==pointType) {
                    MessageInfo messageInfo = new MessageInfo();
                    messageInfo.setMessageAddress(point.getPointId());
                    byte[] data;
                    if(pointType==Const.YC)
                        data = ByteUtil.floatToBytes(point.getValue());
                    else{
                        int temp = (int) point.getValue();
                        data = new byte[]{(byte)temp};
                    }
                    messageInfo.setMessageInfos(data);
                    messageInfo.setQualifiersType(finalQualifiers);
                    messages.add(messageInfo);
                }
            });;

        });

        MessageDetail newMessageDetail = new MessageDetail(control, typeIdentifierEnum, isContinuous, isTest, isPN, transferReason,
                terminalAddress, messageAddress, messages,null, qualifiers);
        ctx.writeAndFlush(newMessageDetail);
    }
}
